<template>
  <div class="app-container">
    <div class="bg_fff mb_12 pl_14">
      <breadcrumb/>
    </div>
    <div class="content-table">
      <div class="form-content">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="用户名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="会员ID" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="请输入会员ID"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="日期范围" prop="timeRange">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-content">
        <div class="table-group">
          <div class="group-right">
            <el-button size="mini" @click="getRoleMgt()" class="addBtn" v-hasPermi="['coordinateList:roleMgt']">默认角色管理</el-button>
            <el-button size="mini" type="primary" @click="handleExport()" class="addBtn" v-hasPermi="['coordinateList:export']">导出</el-button>
            <el-dropdown>
              <el-button type="primary" size="mini" class="customStyle" v-hasPermi="['coordinateList:customList']">
                自定义列表<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" class="columnsFields">
                <el-checkbox-group v-model="columnsFields" @change="handleCheckedChange">
                  <el-checkbox v-for="(item) in tableColumns" :label="item.label" :key="item.label">{{ item.label }}</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div class="table-big">
          <el-table :data="tableDataList"
                    ref="advergroupTable"
                    :max-height="tableHeight"
                    class="tableHightClass"
          >
            <el-table-column :label="item.label" align="center" v-for="(item,index) in tableColumns" :prop="item.key" v-if="item.visible"  :min-width="item.minWidth?item.minWidth:``" :fixed="item.fixed?item.fixed:false" :show-overflow-tooltip="true">
              <!--用于表格自定义-->
              <template slot-scope="scope">
                <!--状态-->
                <div v-if="item.key=='status'">
                  <el-switch v-model="scope.row[item.key]" @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </div>
                <div v-else-if="item.key=='status_name'" class="status">
                  <span :class="scope.row.status==1? `color-green`:`color-red`">{{ scope.row[item.key] }}</span>
                </div>
                <div class="group-btn" v-else-if="item.key=='operate'">
                  <el-tooltip content="编辑" placement="top" effect="light">
                    <el-button type="primary" @click="handleView(scope.row)">详情</el-button>
                  </el-tooltip>
                </div>
                <div v-else>{{ scope.row[item.key] }}</div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>10"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.num"
            @pagination="getList"
          />
        </div>

      </div>
    </div>
    <viewCoordinate v-if="viewCoordinate" :visableIf.sync="viewCoordinate" :id="id" :timeRange="timeRange"></viewCoordinate>
    <roleList v-if="showRoleList" :visableIf.sync="showRoleList"></roleList>
  </div>

</template>
<script>
import { reqCoordinateClose, reqCoordinateList, reqCoordinateOpen, reqCustomCheckStatus, reqAssistToUserIndexExport } from '@/api/coordinateMgt/index'
import { time_date } from '@/utils/validate'

export default {
  name: 'coordinateList',
  components: {
    'viewCoordinate': () => import('./viewCoordinate'),
    'roleList': () => import('./roleList')
  },
  data() {
    return {
      // 查询参数
      total: 8,// 表格的总条数
      viewCoordinate: false,
      showRoleList: false,//角色列表
      tableHeight: null,
      id: null,//id
      timeRange: [],
      queryParams: {
        page: 1,
        num: 10,
        name: '',//名字
        id: null,
        status: null,//状态
        start: null,//开始时间
        end: null//结束时间
      },
      statusList: [
        { value: 0, label: '禁用' },
        { value: 1, label: '启用' }
      ],//状态集合
      tableDataList: [],//表格数据
      checkStatusList: [],//
      tableColumns: [
        { key: 'status', label: `状态开关`, visible: true, fixed: true },
        { key: 'user_login', label: `主账号/手机号`, visible: true, minWidth: 150, fixed: true },
        { key: 'id', label: `主账号ID`, visible: true, minWidth: 150, fixed: true },
        { key: 'status_name', label: `状态`, visible: true, minWidth: 150, fixed: true },
        { key: 'operate', label: `协作者详情`, visible: true, minWidth: 150 },
        { key: 'today_coin', label: `今日充值金额`, visible: true, minWidth: 150 },
        { key: 'all_coin', label: `累计充值总金额`, visible: true, minWidth: 150 },
        { key: 'user_num', label: `当前协作者账户数`, visible: true, minWidth: 150 },
        { key: 'user_use_num', label: `今日有消耗账户数`, visible: true, minWidth: 150 },
        { key: 'today_use_score', label: `协作者今日总消耗（广告币）`, visible: true, minWidth: 200 }
      ],
      exportColumns: [
        { key: 'user_login', label: `主账号/手机号` },
        { key: 'id', label: `主账号ID` },
        { key: 'status_name', label: `状态` },
        { key: 'assist.today_coin', label: `今日充值金额` },
        { key: 'assist.all_coin', label: `累计充值总金额` },
        { key: 'assist.user_num', label: `当前协作者账户数` },
        { key: 'assist.user_use_num', label: `今日有消耗账户数` },
        { key: 'assist.today_use_score', label: `协作者今日总消耗（广告币）` }
      ],
      columnsFields: []//自定义列表的字段集合

    }
  },
  created() {
    let start = this.parseTime(time_date(30).start).split(' ')[0] //本月开始时间
    let end = this.parseTime(time_date(30).end).split(' ')[0]//本月结束时间
    this.timeRange = [start, end]
    this.getList()
    this.tableColumns.forEach(item => {
      this.columnsFields.push(item.label)
    })
    this.getCustomCheckStatus()//资质审核
  },
  watch: {
    tableDataList: {
      handler(val) {
        if (val.length > 0) {
          this.getTabelHeight()//获取表格的最大高度
          this.getTableContentHeight()//获取整体的高度
          this.$refs.advergroupTable.doLayout()
        }

      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getTabelHeight()//获取表格的最大高度
    this.getTableContentHeight()//获取整体的高度
    window.onresize = () => {
      return (() => {
        this.getTabelHeight()//获取表格的最大高度
        this.getTableContentHeight()//获取整体的高度
        this.$refs.advergroupTable.doLayout()
      })()
    }
  },

  methods: {
    getCustomCheckStatus() {
      this.checkStatusList = []
      reqCustomCheckStatus().then(res => {
        for (let key in res.data) {
          let obj = {
            value: key,
            label: res.data[key]
          }
          this.checkStatusList.push(obj)
        }
      })
    },
    getTableContentHeight() {
      let topHeight = document.querySelector('.table-content').offsetTop
      let windowsHeight = document.body.clientHeight
      document.querySelector('.table-content').style.height = windowsHeight - topHeight - 80 + 'px'
    },
    getTabelHeight() {
      //获取表格的高度
      let topHeight = document.querySelector('.tableHightClass').offsetTop
      let windowsHeight = document.body.clientHeight
      if (this.total > 10) {
        let paginationContainerHeight = document.querySelector('.pagination-container').clientHeight
        this.tableHeight = windowsHeight - topHeight - 20 - paginationContainerHeight - 80
      } else {
        this.tableHeight = windowsHeight - topHeight - 20
      }
    },
    selectAll() {
      //全选功能,先进行清除状态，然后再选择是全选还是多选
      this.$refs.advergroupTable.clearSelection()
      this.tableDataList.forEach((row) => {
        this.$refs.advergroupTable.toggleRowSelection(row)
      })
    },
    selectInvert() {
      //反选功能
      let listfiter = this.tableDataList.filter(item => {
        return this.multipleSelection.indexOf(item.id) == -1// 不包含选中的
      })
      console.log('反选过滤', listfiter)
      // 然后进行反选
      this.$refs.advergroupTable.clearSelection()
      if (listfiter && listfiter.length > 0) {
        listfiter.forEach((item) => {
          this.$refs.advergroupTable.toggleRowSelection(item)
        })
      }
    },
    handleCheckedChange(val) {
      console.log('val的值', val)
      //自定义的代码
      this.tableColumns.forEach(item => {
        item.visible = val.includes(item.label);
      });
      console.log('1111',this.tableColumns);
    },
    handleStatusChange(row) {
      console.log('状态', row.status)
      let text = row.status == false ? '暂停' : '启用'
      this.$modal.confirm(`确认要${text}此账号（${row.user_login}）吗？`).then(function() {
        if (row.status == false) {
          return reqCoordinateClose(row.id)
        } else {
          return reqCoordinateOpen(row.id)

        }
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
        this.getList()
      }).catch(function() {
        row.status = row.status == 1 ? false : true
      })
    },
    getList() {
      this.tableDataList = []
      this.loading = true
      if (this.timeRange && this.timeRange.length > 0) {
        this.queryParams.start = this.timeRange[0]
        this.queryParams.end = this.timeRange[1]
      } else {
        this.queryParams.start = null
        this.queryParams.end = null
      }
      reqCoordinateList(this.queryParams).then(res => {
          this.tableDataList = res.data.list
          this.tableDataList.forEach(item => {
            item.today_coin = item.assist.today_coin //充值金额
            item.all_coin = item.assist.all_coin //累计充值总金额
            item.today_use_score = item.assist.today_use_score //今日实时消耗（广告币）
            item.user_use_num = item.assist.user_use_num
            item.user_num = item.assist.user_num
            item.status = item.status == 1 ? true : false
          })
          this.total = res.data.count
          this.loading = false

        }
      )
    }
    ,
    //搜索
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    //重置表单
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    //详情
    handleView(row) {
      this.id = row.id
      this.viewCoordinate = true
    },
    /** 导出按钮操作 */
    handleExport() {
      let form = JSON.parse(JSON.stringify(this.queryParams))
      let head = []
      let keys = []
      this.exportColumns.forEach(item => {
        this.tableColumns.forEach(sitem => {
          if (sitem.label == item.label) {
            if (head.indexOf(item.label) == -1) {
              head.push(item.label)
            }
            if (keys.indexOf(item.key) == -1) {
              keys.push(item.key)
            }
          }

        })
      })
      form.head = head
      form.keys = keys
      delete form.page
      delete form.num
      reqAssistToUserIndexExport(form).then((res) => {
        console.log('333', res)
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '协同管理列表数据.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })

    },
    getRoleMgt() {
      this.showRoleList = true
    }

  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .big-title {
    height: 40px;
    border-bottom: 1px solid #D5D5D5;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0px 24px;
  }

  .form-content {
    padding: 12px;
    background: #fff;
    margin-bottom: 10px;
  }

  /*表格通用代码编写，可用于全局*/
  .table-content {
    background: #fff;
    padding: 0px 15px;

    .table-group {
      display: flex;
      padding: 12px 0px;
      flex-wrap: wrap;

      .group-left {
        width: 200px;
        display: flex;
        flex-wrap: wrap;

        ::v-deep.el-button--primary {
          border: 1px solid #1670F1;
          background: none !important;
          color: #1670F1;
        }
      }

      .group-right {
        flex: 1;
        align-items: center;
        justify-content: flex-end;
        display: flex;

        .suspendBtn {
          background: #FB311E !important;
          border-color: #FB311E;
        }

        .exportBtn, .customStyle {
          border: 1px solid #1670F1;
          background: none !important;
          color: #1670F1;
        }
      }

    }

    /*表格样式*/
    .table-big {
      ::v-deep .el-table {
        .links {
          color: #1670F1;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }

  }

}

.tableList {
  display: flex;
  border-bottom: 1px solid #eee;
  background: #fff;
  padding: 0px 20px;
  margin: 0;
  height: 54px;
  border-bottom: 10px solid #F8F9FD;
  margin: 16px 0px 0 0px;

  li {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    padding: 0px 10px;
    position: relative;
    cursor: pointer;
    height: 44px;
    color: #8E8E8E;
    margin-right: 30px;

    &.active {
      font-weight: bold;
      color: #000;

      &:after {
        height: 2px;
        background: #1670F1;
        content: '';
        position: absolute;
        left: 10px;
        right: 10px;
        bottom: 0;

      }
    }
  }
}

.status {
  span {
    position: relative;
    padding-left: 15px;

    &:after {
      position: absolute;
      left: 0px;
      width: 9px;
      height: 9px;
      border-radius: 50%;
      content: '';
      top: 50%;
      margin-top: -4.5px;
    }

    &.color-green:after {

      background: #00DD33;


    }

    &.color-red:after {
      background: #D10807;
    }
  }

}

.columnsFields {
  overflow-y: auto;
  padding: 10px 10px;

  .el-checkbox-group {
    display: flex;
    flex-direction: column;

    .el-checkbox {
      width: 200px;
      margin-bottom: 5px;
    }
  }
}

.el-dropdown {
  margin-left: 10px;
}
</style>
